'use strict'

const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const fav = require('./lib/favicon')
const error = require('./lib/error')
const config = require('./lib/config')

const json = config.getDefalutConfig()

console.log('http.js start.....')

const server = http.createServer(function (request, response) {
    // console.log("request=%o",request.headers)
    console.log("request = {}",request.url)
    if (request.url === '/favicon.ico') {
        return fav.favicon(__dirname + '/favicon.ico',response)
    }
    // 解析请求，包括文件名
    let pathname = url.parse(request.url).pathname
    let basename = path.basename(pathname)
    if (basename == null || basename == '') {
        return response.end()
    }
    // 输出请求的文件名
    console.log("Request for " + pathname + " received. base name = " + basename)
    let filename = path.join(__dirname + pathname)
    if (fs.existsSync(filename) === false) {
        return error.error(__dirname, response)

    }
    fs.readFile(filename, (err, data) => {
        if (err) {
            console.log('err message = ', err.message)
            response.statusCode = 404
            response.end()
        } else {
            // response.writeHead(200, { 'Content-Type': 'text/html' })
            response.writeHead(200)
            response.write(data)
            response.end()
        }
    })
})


server.listen(json.port)

console.log('server start in port ', json.port)